package application.ratt.user_interface;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;

import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import application.ratt.R;
import application.ratt.data_reader.MainClass;
import application.ratt.exceptions.InterruptRequestException;
import application.ratt.utils.RoutesXMLParser;
import android.app.ProgressDialog;
import android.widget.Spinner;

public class MainActivity extends Activity implements TextWatcher, OnItemClickListener, OnItemSelectedListener{

    private float currentLocationLatitude = 0;
    private float currentLocationLongitude = 0;
    private float desiredDestinationLatitude = 0;
    private float desiredDestinationLongitude = 0;
    
    private AutoCompleteTextView currentLocationAutoText;
    private ProgressBar currentLocationProgress;
    private AutoCompleteTextView desiredDestinationAutoText;
    private Button findRouteButton; 
    private Button useGPSButton;
    private ProgressBar calculatingRouteProgress;
    private Spinner spinner_routes;
    private Spinner spinner_wdStart;
    private Spinner spinner_wdStop;
    
    private ArrayAdapter<String> locAutoCompleteAdapter;
    private List<Address> locAutoCompleteAddresses;
    private ArrayAdapter<String> destAutoCompleteAdapter;
    private List<Address> destAutoCompleteAddresses;
    private Handler messageHandler;
    
    private static final int MESSAGE_TEXT_CHANGED = 0;
    private static final int AUTOCOMPLETE_DELAY = 100;
    private static final int THRESHOLD = 3;
    
    public static final String PREFS_NAME = "MyPrefsFile";
    
    public SharedPreferences settings = null;
    private SharedPreferences.Editor editor;
	
	private static final String cachedDataFileName = "routes.xml";
	private static final String dbFileName = "linestations.csv";
	
	private String selectedAddress = "";
	
	private static final String[] routes = { "1 route", "2 routes", "3 routes"};
	private static final String[] walkDistances = {"500 m", "750 m", "1000 m"};
	
	private InputStream resultsInputStream = null;
	private final MainClass cls =  MainClass.getInstance();
	
	private AlertDialog.Builder builderCalculateRoutes = null;
	private File cachedDataFile = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		settings = getSharedPreferences(PREFS_NAME, 0);
		editor = settings.edit();
		
		getComponents();
		messageHandler = new MyMessageHandler(this);	
		createAdapters();
		
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
	}
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		currentLocationProgress.setVisibility(ProgressBar.INVISIBLE);
		calculatingRouteProgress.setVisibility(ProgressBar.INVISIBLE);
		findRouteButton.setVisibility(Button.VISIBLE);
		useGPSButton.setVisibility(Button.VISIBLE);
	}
	
	private void getComponents()
	{
		currentLocationAutoText = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView2);
		currentLocationProgress = (ProgressBar)findViewById(R.id.progressBar1);
		desiredDestinationAutoText = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
		calculatingRouteProgress = (ProgressBar)findViewById(R.id.progressBar2); 
		findRouteButton = (Button) findViewById(R.id.button2); 
		useGPSButton = (Button) findViewById(R.id.button1);
		spinner_routes = (Spinner) findViewById(R.id.spinner_nrRoutes);
		spinner_wdStart = (Spinner) findViewById(R.id.spinner_wdStart);
		spinner_wdStop = (Spinner) findViewById(R.id.spinner_wdStop);
	}
	
	private void createAdapters()
	{
		locAutoCompleteAdapter = new ArrayAdapterNoFilter(this, R.layout.dropdown_list);
		locAutoCompleteAdapter.setNotifyOnChange(false);
		
		String text1 = settings.getString("currentLocationAutoText", "");
		if (!text1.equals("")){
			currentLocationAutoText.setText(text1);
		}
		
		String text2 = settings.getString("desiredDestinationAutoText", "");
		if (!text2.equals("")){
			desiredDestinationAutoText.setText(text2);
		}
		
		currentLocationAutoText.addTextChangedListener(this);
		currentLocationAutoText.setOnItemClickListener(this);
		currentLocationAutoText.setThreshold(THRESHOLD);
		currentLocationAutoText.setAdapter(locAutoCompleteAdapter);
		
	    destAutoCompleteAdapter = new ArrayAdapterNoFilter(this, R.layout.dropdown_list);
	    destAutoCompleteAdapter.setNotifyOnChange(false);
	    desiredDestinationAutoText.addTextChangedListener(this);
	    desiredDestinationAutoText.setOnItemClickListener(this);
	    desiredDestinationAutoText.setThreshold(THRESHOLD);
	    desiredDestinationAutoText.setAdapter(destAutoCompleteAdapter);
	    
	    ArrayAdapter<String> adapter_routes = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, routes);
		adapter_routes.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_routes.setAdapter(adapter_routes);
        spinner_routes.setOnItemSelectedListener(this);
        
        ArrayAdapter<String> adapter_walkDistance = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, walkDistances);
		adapter_walkDistance.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_wdStart.setAdapter(adapter_walkDistance);
        spinner_wdStart.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				String selectedItemValue;
				selectedItemValue = parent.getSelectedItem().toString().split(" ")[0];
				editor.putInt("walkDistanceFromStart", Integer.parseInt(selectedItemValue));
				editor.commit();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				editor.putInt("walkDistanceFromStart", Integer.parseInt(walkDistances[0]));
				editor.commit();
			}
		});
        
        	spinner_wdStart.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (MotionEvent.ACTION_UP == event.getAction()){
					Toast.makeText(MainActivity.this, R.string.select_distance_from_start, Toast.LENGTH_SHORT).show();
				}
				return false;
			}
		});
        
        ArrayAdapter<String> adapter_walkDistanceToStop = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, walkDistances);
		adapter_walkDistanceToStop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_wdStop.setAdapter(adapter_walkDistanceToStop);
        
        spinner_wdStop.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				String selectedItemValue;
				selectedItemValue = parent.getSelectedItem().toString().split(" ")[0];
				editor.putInt("walkDistanceToStop", Integer.parseInt(selectedItemValue));
				editor.commit();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				editor.putInt("walkDistanceToStop", Integer.parseInt(walkDistances[0]));
				editor.commit();
			}
		});
        
        spinner_wdStop.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (MotionEvent.ACTION_UP == event.getAction()){
					Toast.makeText(MainActivity.this, R.string.select_distance_to_destination, Toast.LENGTH_SHORT).show();
				}
				return false;
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	/** Called when the user clicks the use GPS button */
	public void useGPS(View view) {
		
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	    final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		
	    if (!gpsEnabled)
	    {
	    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    	
	    	builder.setMessage(R.string.GPS_alert_text)
	    	       .setTitle(R.string.warning_message_title);

	    	builder.setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int id) {
	                // User clicked OK button
	            	Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	                startActivity(settingsIntent);    
	            }
	        });
	        builder.setNegativeButton(R.string.GPS_alert_cancel, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int id) {
	                // User cancelled the dialog
	            }
	        });
	        
	        AlertDialog dialog = builder.create();
	        dialog.show();
	    }
	    else
	    {    
	    	useGPSButton.setVisibility(Button.INVISIBLE);
	    	currentLocationProgress.setVisibility(ProgressBar.VISIBLE);
	    	LocationListener locationListener = new LocationListener()
	    	{
	            public void onLocationChanged(Location location)
	            {
	                updateLocation(location);
	            }
	            public void onStatusChanged( String provider, int status, Bundle extras) {}
	            public void onProviderEnabled(String provider) {}
	            public void onProviderDisabled(String provider) {}
	        };	        
	        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, (long)30000, (float) 10.0, locationListener);
	    }
	}
	
	void updateLocation(Location location)
    {
        currentLocationLatitude = (float)location.getLatitude();
        currentLocationLongitude = (float)location.getLongitude();
        getAddress();
    }
	
	void getAddress()
	{
        try{
            Geocoder gcd = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = 
                gcd.getFromLocation(currentLocationLatitude, currentLocationLongitude,100);
            if (addresses.size() > 0)
            {
            	StringBuilder result = new StringBuilder();
                Address address =  addresses.get(0);
                int maxIndex = address.getMaxAddressLineIndex();
                for (int x = 0; x <= maxIndex; x++ )
                {
                   result.append(address.getAddressLine(x));
                   if (x != maxIndex - 1) {
	                    result.append(", ");
	                }
                }               
                currentLocationProgress.setVisibility(ProgressBar.INVISIBLE);
    	    	currentLocationAutoText.setVisibility(EditText.VISIBLE);
    	    	currentLocationAutoText.setText(result.toString());
    	    	editor.putString("currentLocationAutoText", result.toString());
    	    	editor.commit();
            }
        }
        catch(IOException ex){
        	
        	currentLocationProgress.setVisibility(ProgressBar.INVISIBLE);
        	currentLocationAutoText.setVisibility(EditText.VISIBLE);
        	currentLocationAutoText.setText(ex.getMessage().toString());
        }
    }
	
	/** Called when the user clicks the find route */
	public void findRoute(View view) {
		findRouteButton.setVisibility(Button.INVISIBLE);
		calculatingRouteProgress.setVisibility(ProgressBar.VISIBLE);
		String text1 = currentLocationAutoText.getText().toString();
		editor.putString("currentLocationAutoText", text1);
		String text2 = desiredDestinationAutoText.getText().toString();
		editor.putString("desiredDestinationAutoText", text2);
		
    	editor.commit();
    	findRouteButton.setEnabled(false);
    	
    	builderCalculateRoutes = new AlertDialog.Builder(this);
    	new CalculateRoutesAsyncTask().execute();
	}
	
	private void switchToResultActivity(){
		Intent resultActivity = new Intent(this, ResultsActivity.class);
        startActivity(resultActivity);
	}
	
	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
	    messageHandler.removeMessages(MESSAGE_TEXT_CHANGED);
	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
	String value = arg0.toString();
	if (!"".equals(value) && value.length() >= THRESHOLD)
	{
	    Message msg = Message.obtain(messageHandler, MESSAGE_TEXT_CHANGED, arg0.toString());
	    messageHandler.sendMessageDelayed(msg, AUTOCOMPLETE_DELAY);
	} 
	else {
			clearAutocompleteAdapter();
	}
	}

	@Override
	public void afterTextChanged(Editable arg0) {
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{
		if (currentLocationAutoText.isFocused())
		{
			if (arg2 < locAutoCompleteAddresses.size()) {
				selectedAddress = arg0.getItemAtPosition(arg2).toString();
		        Address selected = locAutoCompleteAddresses.get(arg2);
		        currentLocationLatitude = (float)selected.getLatitude();
		        currentLocationLongitude = (float)selected.getLongitude();
		        desiredDestinationAutoText.requestFocus();
		    }
		}
		else
		{
			if (desiredDestinationAutoText.isFocused())
			{
				if (arg2 < destAutoCompleteAddresses.size()) {
					selectedAddress = arg0.getItemAtPosition(arg2).toString();
			        Address selected = destAutoCompleteAddresses.get(arg2);
			        desiredDestinationLatitude = (float)selected.getLatitude();
			        desiredDestinationLongitude = (float)selected.getLongitude();
			        currentLocationAutoText.requestFocus();
			        InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			        mgr.hideSoftInputFromWindow(desiredDestinationAutoText.getWindowToken(), 0);
			    }
			}
		}
		editor.putFloat("currentLocationLatitude", currentLocationLatitude);
		editor.putFloat("currentLocationLongitude", currentLocationLongitude);
		editor.putFloat("desiredDestinationLatitude", desiredDestinationLatitude);
		editor.putFloat("desiredDestinationLongitude", desiredDestinationLongitude);
		
		editor.commit();
	}

	private void notifyResult(List<Address> suggestions) {
		setAutocompleteAdapter(suggestions);
		clearAutocompleteAdapter();
	    for (Address a : suggestions)
	    {
	    	if (a!= null)
	    	{
	    			StringBuilder mSb = new StringBuilder();
		    		final int addressLineSize = a.getMaxAddressLineIndex();
		            for (int i = 0; i < addressLineSize; i++) {
		                mSb.append(a.getAddressLine(i));
		                if (i != addressLineSize - 1) {
		                    mSb.append(", ");
		                }
		            }		            
		            notifyAutocompleteAdapter(mSb.toString());
	    	}
	    }
	}
	
	private void setAutocompleteAdapter(List<Address> address)
	{
		if (currentLocationAutoText.isFocused())
		{
			locAutoCompleteAddresses = address;
		}
		else
		{
			if (desiredDestinationAutoText.isFocused())
			{
			    destAutoCompleteAddresses = address;
			}
		}
	}
	
	private void clearAutocompleteAdapter()
	{
		if (currentLocationAutoText.isFocused())
		{
			locAutoCompleteAdapter.clear();
		}
		else
		{
			if (desiredDestinationAutoText.isFocused())
			{
			    destAutoCompleteAdapter.clear();
			}
		}
	}
	
	private void notifyAutocompleteAdapter(String text)
	{
		if (currentLocationAutoText.isFocused())
		{
			locAutoCompleteAdapter.add(text);
			locAutoCompleteAdapter.notifyDataSetChanged();
			currentLocationAutoText.clearListSelection();
		}
		else
		{
			if (desiredDestinationAutoText.isFocused())
			{
				destAutoCompleteAdapter.add(text);
	            destAutoCompleteAdapter.notifyDataSetChanged();
	            desiredDestinationAutoText.clearListSelection();
			}
		}
	}
	
	@SuppressLint("HandlerLeak")
	private class MyMessageHandler extends Handler {

		private Context context;

		public MyMessageHandler(Context context) {
			this.context = context;
		}

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == MESSAGE_TEXT_CHANGED) {
				if (!selectedAddress.equals(msg.obj.toString())) {
					String enteredText = (String) msg.obj;
					Geocoder geo = new Geocoder(context);
					new MyAsynkTask().execute(enteredText, geo);
				}
			}
		}
	}
	
	private void showPopupDialog(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.alert_exception);
		
		builder.setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
            }
        });
		
		AlertDialog dialog = builder.create();
        dialog.show();
        
        findRouteButton.setVisibility(Button.VISIBLE);
    	calculatingRouteProgress.setVisibility(ProgressBar.INVISIBLE);
	}
	
	private class MyAsynkTask extends AsyncTask<Object, Void, List<Address>>
	{
	   	protected List<Address> doInBackground(Object... info)
	   	{
	   		List<Address> Suggestions = null;
	   		try
	   		{
	   			Suggestions = ((Geocoder)info[1]).getFromLocationName((String)info[0], 5, 45.67, 21.36, 45.82, 21.08);
	   		}
	   		catch (Exception ex)
            {
	   			Log.e("TEST", "exception", ex);
            } 	   		
	   		return Suggestions;
	    }
	   	
	   	@Override
	   	protected void onPostExecute(List<Address> result)
	   	{
	   		if (result != null &&
	   			result.size() != 0)
                {
                   notifyResult(result);  
                }
	   	}
	 }
	
	private class CalculateRoutesAsyncTask extends AsyncTask<Void, Integer, Void>{
 		 
		private boolean failed = false;
		private boolean interrupted = false;
		public boolean backtwice=false;
		
        private ProgressDialog pd = new ProgressDialog(MainActivity.this);

		@Override
		protected void onPreExecute() {
			// update the UI immediately after the task is executed
			super.onPreExecute();
			pd.setMessage("Loading...");
			pd.setOnKeyListener(new OnKeyListener() {

				@Override
				public boolean onKey(DialogInterface arg0, int arg1, KeyEvent event) {
					// TODO Auto-generated method stub
					if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
						if (!backtwice){
							backtwice = true;
							
				    	builderCalculateRoutes.setMessage(R.string.stopping_request).setTitle(R.string.warning_message_title);
				    	builderCalculateRoutes.setPositiveButton("OK", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								cls.setInterruptRequest(true);
							}
						});
				    	builderCalculateRoutes.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								
							}
						});
				    	builderCalculateRoutes.show();
						}
						else
						{
							backtwice = false;
						}
				      }
					return false;
				}
			});
			pd.show();
		}
 	      
		@Override
		protected Void doInBackground(Void... params) {

			float currentLat = settings.getFloat("currentLocationLatitude",	0.0f);
			float currentLong = settings.getFloat("currentLocationLongitude", 0.0f);
			float desireLat = settings.getFloat("desiredDestinationLatitude", 0.0f);
			float desireLong = settings.getFloat("desiredDestinationLongitude",	0.0f);
			int nrOfRoutes = settings.getInt("nrOfRoutes", 1);
			
			// clear parsed list before is populated again
			RoutesXMLParser.getRoutes().clear();

			File filesRootDir = getFilesDir();

			try {
				AssetManager assetManager = getAssets();
				InputStream dbInputStream = assetManager.open(dbFileName);

				cachedDataFile = new File(filesRootDir + "/text/",	cachedDataFileName);
//				cachedDataFile.createNewFile();
				cls.setCoordinates(currentLat, currentLong, desireLat, desireLong);
				cls.calculateRoute(dbInputStream, cachedDataFile, settings, nrOfRoutes);
				
				resultsInputStream = new BufferedInputStream(new FileInputStream(cachedDataFile));
				RoutesXMLParser.parseXML(resultsInputStream);
			}
			catch (InterruptRequestException e){
				e.printStackTrace();
				interrupted = true;
			}
			catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				failed = true;
			}
			return null;
		}
 	  
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}
 	   
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			pd.dismiss();
			findRouteButton.setEnabled(true);
			calculatingRouteProgress.setVisibility(ProgressBar.INVISIBLE);
			findRouteButton.setVisibility(Button.VISIBLE);
			findRouteButton.setEnabled(true);
			if (failed){
				showPopupDialog();
			}
			else if (!interrupted){
				switchToResultActivity();
			}
		}
    }

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		// TODO Auto-generated method stub
		editor.putInt("nrOfRoutes", pos + 1);
    	editor.commit();
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub
		editor.putInt("nrOfRoutes", 1);
    	editor.commit();
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

	    switch (item.getItemId()) {
	    case R.id.action_exit:
	    	this.finish();
	    	break;
	    case R.id.action_clean:
	    	editor.clear();
	    	editor.commit();
	    	currentLocationAutoText.getEditableText().clear();
	    	desiredDestinationAutoText.getEditableText().clear();
	    	spinner_routes.setSelection(0);
	    	spinner_wdStart.setSelection(0);
	    	spinner_wdStop.setSelection(0);
	    	if (cachedDataFile != null){
	    		cachedDataFile.delete();
	    	}
	    	return true;
	    case R.id.action_display_results:
	    	boolean newRunning = false;
	    	
			if (cachedDataFile == null) 
			{
				File filesRootDir = getFilesDir();
				cachedDataFile = new File(filesRootDir + "/text/",	cachedDataFileName);
				newRunning = true;
			}
			if (cachedDataFile.length() == 0)
			{
				showNoResultsPopup();
			}else
			{
				if (newRunning){
					switchToResultActivity();
					Toast.makeText(MainActivity.this, R.string.old_results_warning, Toast.LENGTH_SHORT).show();
				}
				else{
					switchToResultActivity();
				}
			}
	    	break;
	    default:
	        break;
	    }
	    return super.onOptionsItemSelected(item);
	}
	
	private void showNoResultsPopup(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setMessage(R.string.no_results_message).setTitle(
				R.string.warning_message_title);
		AlertDialog dialog = builder.create();
		dialog.show();
    }
}
